package com.xj.toOffer.nowCoder;

/**
 * @author: xujiang
 * @createTime: 2021/7/21 14:20:47
 */
public class JZ14 {

    public static int len = 0;

    public ListNode FindKthToTail(ListNode pHead, int k) {
        // write code here
        if (pHead == null || k == 0) {
            return null;
        }
        int nodeLength = getNodeLength(pHead);
        if (nodeLength < k) {
            return null;
        }
        while (nodeLength != k) {
            pHead = pHead.next;
            nodeLength --;
        }
        return pHead;

    }
    private int getNodeLength(ListNode node) {
        ListNode p = node;
        int len = 0;
        while (p!=null) {
            len++;
            p= p.next;
        }
        return len;
    }

    public static void main(String[] args) {
        ListNode p = new ListNode(1);
        JZ14 jz14 = new JZ14();
        jz14.addNode(p, 2);
        jz14.addNode(p, 3);
        jz14.addNode(p, 4);
        jz14.addNode(p, 5);
//        prinNodeList(p);
        ListNode node = jz14.FindKthToTail(p, 5);
        System.out.println(node.val);
    }


    private static void prinNodeList(ListNode p) {
        while (p!=null) {
            System.out.println(p.val);
            p = p.next;
        }
    }

    public ListNode addNode(ListNode a, int val) {
        ListNode node = new ListNode(val);
        ListNode t = a;
        while (t.next != null) {
            t = t.next;
        }
        t.next = node;
        return a;
    }

}